<template>
	<view class="venue" :style="css.page+'min-height:'+$xyfun.xysys().windowHeight+'px'">
		<view class="p-lr-30 p-tb-15 tc-r bc-w m-b-2 ts-28 tc" :style="css.tcp">提示：订单需在五分钟内支付，超时自动关闭。</view>
		<view class="date-wrapper p-t-20 bc-w">
			<DateTabs :value.sync="curDate" :color="css.style.mainColor" :bgColor="css.style.pageModuleBgColor"
				@change="changeDate"></DateTabs>
		</view>
		<!-- <view class="venue-tab p-30 m-t-10 bc-w">
			<scroll-view scroll-x="true">
				<view class="item p-lr-30 m-r-30 m-b-20" v-for="(item, keys) in venueList" :key="keys"
					:style="item.id == curVenueId ? css.mcbg : css.pbg" @tap="changeVenue(item.id)">
					<text :class="item.id == curVenueId ? 'tc-w' : ''">{{item.name}}</text>
				</view>
			</scroll-view>
		</view> -->

		<view class="tip-box flex p-30 ts-28 bc-w m-t-10">
			<view class="col-3 lh-30 flexc">
				<view class="b" :style="css.mcbg"></view>可选
			</view>
			<view class="col-3 lh-30 flexc">
				<view class="b" :style="css.bch"></view>已售
			</view>
			<view class="col-3 lh-30 flexc">
				<view class="b" :style="css.prbg"></view>选中
			</view>
		</view>

		<view class="list-box p-lr-30 p-t-20 p-b-40 flex bc-w m-t-10">
			<view class="l">
				<view class="item ts-26" v-for="(item, keys) in allVenues[0].timeprice" :key="keys">
					{{item.time}}
				</view>
			</view>
			<view class="r">
			  <scroll-view scroll-x="true">
			    <view class="list">
			      <!-- 使用 scroll-view 横向滚动显示每个 curVenue 的 area -->
			      <!-- <scroll-view scroll-x="true"> -->
			        <!-- 使用 v-for 遍历 allVenues 数组中的每个 curVenue -->
			        <view v-for="(venue, venueIndex) in allVenues" :key="venueIndex" class="scroll-container">
			          <!-- 使用 renderDynamicArray 渲染每个 curVenue 的 area -->
			          <text class="item tc p-lr-20 ts-26 m-b-10 m-r-20 br-10"
			            v-for="(element, index) in renderDynamicArray(venue.area)" :key="index">
			            {{ element }}
			          </text>
			        </view>
			      <!-- </scroll-view> -->
			    </view>

				<view class="list" v-for="(item, keys) in mergedYdList" :key="keys">
					<view class="item p-lr-20 tc sc tc-w br-10 m-b-20 m-r-15 " v-for="(item1, keys1) in item.area"
						:key="keys1" :style="item1.isSelect ? css.prbg : (!item1.isBuy ? css.mcbg : css.bch)"
						@tap="selectArea(item1)">
						<text class="ts-26" v-if="!item1.isBuy">¥{{item1.price}}</text>
					</view>
				</view>
			    <!-- <view v-for="(venue, venueIndex) in allVenues" :key="venueIndex">
			      <view class="list" v-for="(item, keys) in venue.ydList" :key="keys">
			        <view class="item tc sc tc-w br-10 m-b-10 m-r-15" v-for="(item1, keys1) in item.area"
			          :key="keys1" :style="item1.isSelect ? css.prbg : (!item1.isBuy ? css.mcbg : css.bch)"
			          @tap="selectArea(item1)">
			          <text class="ts-26" v-if="!item1.isBuy">¥{{item1.price}}</text>
			        </view>
			      </view>
			    </view> -->

			  </scroll-view>
			</view>
		</view>
		<view class="bottom-fixed flex tc bc-w">
			<view class="p-lr-30 p-tb-15 flex tc wa">
				<view class="lh-32 p-t-20 ts-32 m-r-30"><text>合计：</text><text class="ts-26"
						:style="css.tcp">¥</text><text :style="css.tcp">{{ $xyfun.pea(totalAmount) }}</text></view>
				<view class="action flex m-l-auto">
					<block>
						<view class="buy m-l-auto tb tc-w" :style="css.mcbg" @tap="subOrder()">
							提交订单
						</view>
					</block>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import DateTabs from '@/uni_modules/hope-11-date-tabs/components/hope-11-date-tabs/date-tabs.vue'

	export default {
		components: {
			DateTabs,
		},
		data() {
			return {
				css: {},
				lat: 0,
				lng: 0,
				search: '',
				storeList: [],
				isLoading: true,
				store_id: 0,
				currentPage: 1,
				lastPage: 1,
				loadStatus: 'loadmore',
				mergedYdList:[],
				venueList: [],
				curVenueId: 0,
				curVenue: {},
				allVenues: {},
				curDate: '',
				totalAmount: 0,
				buyItem: []
			}
		},
		computed: {
			...mapState(['common'])
		},
		onLoad(options) {
			this.$xyfun.setNavBg();
			this.css = this.$xyfun.css();
			if (options) {
				this.curVenueId = options.venue_id;
			}
			this.$xyfun.loc().then((res) => {
				this.lat = res.latitude;
				this.lng = res.longitude;
				this.loadData();
			}, () => {
				this.loadData();
			})
		},
		onPullDownRefresh() {
			this.currentPage = 1;
			this.storeList = [];
			this.loadData();
		},
		methods: {
			loadData() {
				this.$xyfun.storeId().then((store_id) => {
					this.store_id = store_id;
					this.$api.get({
						url: '/venue/init',
						loadingTip: '加载中...',
						data: {
							store_id: store_id,
							venue_id: this.curVenueId,
							buy_date: this.curDate,
						},
						success: res => {
							uni.stopPullDownRefresh();
							this.isLoading = false;
							this.venueList = res.venueList;
							this.allVenues = res.allVenuesData;
							// 假设 this.allVenues 是从接口获取到的所有场馆数据
							const allVenues = res.allVenuesData;
							allVenues.forEach(venue => {
							  venue.ydList.forEach(ydItem => {
							    ydItem.area.forEach(area => {
							      // 为每个 area 增加 venue_id 字段，值为当前 venue 的 id
							      area.venue_id = venue.id;
							    });
							  });
							});
							// 初始化一个空的ydList数组
							let mergedYdList = [];
							// 遍历所有场馆
							allVenues.forEach(venue => {
							  venue.ydList.forEach(slot => {
							    // 查找 mergedYdList 中是否已存在相同时间的记录
							    let existingTimeSlot = mergedYdList.find(item => item.time === slot.time);
							    if (existingTimeSlot) {
							      // 如果时间已经存在，将新的 area 合并进去
							      existingTimeSlot.area = existingTimeSlot.area.concat(slot.area);
							    } else {
							      // 如果时间不存在，创建一个新的时间段
							      mergedYdList.push({
							        time: slot.time,
							        area: [...slot.area] // 新时间段的 area 需要创建一个新的数组避免引用问题
							      });
							    }
							  });
							});
							// 按时间排序 mergedYdList
							mergedYdList = mergedYdList.sort((a, b) => {
							  return a.time.localeCompare(b.time); // 假设 time 的格式是 HH:mm，可以直接比较
							});
							 // 存储合并后的数据到 data 中
							this.mergedYdList = mergedYdList;
							// console.log(JSON.stringify(mergedYdList, null, 2)); // 美化输出
						},
						fail() {

						}
					});
				})
			},

			//提交订单
			subOrder() {
				if (this.totalAmount > 0) {
					this.$api.post({
						url: '/order/add',
						//loadingTip:'加载中...',
						data: {
							store_id: this.store_id,
							venue_id: this.buyItem[0].venue_id,
							buy_item: this.buyItem,
							total_amount: this.totalAmount,
							buy_date: this.curDate
						},
						success: res => {
							this.$xyfun.to('/pages/user/order/pay?order_id=' + res.id);
						},
						fail() {

						}
					});
				} else {
					this.$xyfun.msg('请选择预定区域');
				}
			},

			//切换日期
			changeDate(e) {
				this.curDate = e.dd;
				this.buyItem = [];
				this.loadData();
			},

			//切换场地
			changeVenue(id) {
				this.curVenueId = id;
				this.buyItem = [];
				this.loadData();
			},

			//选择场地
			selectArea(item) {
				if (!item.isBuy) {
					item.isSelect = !item.isSelect;
					var buyItem = this.buyItem;
					if (buyItem.length == 0) {
						buyItem.push(item);
					} else {
						var flag = false;
						buyItem.forEach((i, k) => {
							if (item.id == i.id) {
								flag = true;
								buyItem.splice(k, 1);
							}
						});
						if (!flag) {
							buyItem.push(item);
						}
					}
					this.buyItem = buyItem;

					var totalAmount = 0;
					buyItem.forEach((i1) => {
						totalAmount += parseFloat(i1['price']);
					})
					this.totalAmount = totalAmount;
				}
			},

			renderDynamicArray(arr) {
				const result = [];

				function recursiveRender(subArr) {
					subArr.forEach((element) => {
						if (Array.isArray(element)) {
							recursiveRender(element);
						} else if (typeof element === 'object' && 'name' in element) {
							result.push(element.name);
						}
					});
				}
				recursiveRender(arr);
				return result;
			}
		}
	}
</script>

<style scoped lang="scss">
	.venue {
		padding-bottom: 200rpx;
	}

	.bottom-fixed {
		.buy {
			width: 260rpx;
			height: 72rpx;
			border-radius: 36rpx;
			line-height: 72rpx;
		}
	}

	.venue-tab {
		scroll-view {
			height: 60rpx;
			white-space: nowrap;
			width: 100%;
		}

		.item {
			height: 60rpx;
			line-height: 60rpx;
			border-radius: 30rpx;
			display: inline-block;
		}

	}

	.sc {
		overflow-x: scroll;
	}

	.sc::-webkit-scrollbar {
		display: none;
	}

	.tip-box .b {
		width: 30rpx;
		height: 30rpx;
		margin-right: 10rpx;
	}

	.list-box {
		.l {
			width: 100rpx;

			.item {
				line-height: 15rpx;
				height: 26rpx;
				margin-top: 58rpx;
			}
		}

		.r {
			width: 590rpx;

			.list {
				padding: 0;
				margin: 0;
				height: 84rpx;
			}

			.item {
				display: inline-block;
				width: 100rpx;
				height: 58rpx;
				line-height: 58rpx;
			}
			
		}

		scroll-view {
			white-space: nowrap;
		}

	}
	
	.scroll-container {
	  display: inline-block;
	}
	.item {
	  display: inline-block;
	  margin-right: 20px; /* 控制横向间距 */
	}
</style>